const fs = require('fs'); // 文件读写模块
const pdfConverter = require('pdf-to-png-converter'); // PDF转换canvas的功能模块
const path = require('path'); // 路径模块
const inputFolder = './PDFS'; // PDF文件所在的文件夹
const outputFolder = './images'; // 转换后的PNG文件存放的文件夹

// 读取文件夹
fs.readdir(inputFolder, async (err, files) => {
  if (err) {
    console.error('读取文件夹失败：', err);
    return;
  }
  const functions = files.map((file) => () => {
    // 模拟异步操作，如读取文件或网络请求
    return new Promise(async (resolve, reject) => {
      if (path.extname(file).toLowerCase() === '.pdf') {
        const pdfPath = path.join(inputFolder, file);
        const outputPath = path.join(outputFolder, path.basename(file, '.pdf'));
        console.log(file, '开始解析.....');
        pdfToPng(pdfPath, outputPath);
        resolve();
      }
    });
  });

  executeEveryFive(functions); // 执行并发序列
});

// 执行并发序列
const executeEveryFive = (functionsQueue, concurrency = 10) => {
  let executed = 0;
  let queue = functionsQueue.slice(); // 复制函数队列
  const executeNextFive = () => {
    let batch = queue.splice(0, concurrency); // 取出前五个函数
    let promises = batch.map((func) => func()); // 执行这批函数
    console.log(`第${executed + 1}轮解析开始 --- 文件组`);
    Promise.all(promises)
      .then((results) => {
        // 处理结果
        executed += batch.length;
        if (queue.length > 0) {
          setTimeout(executeNextFive, 100); // 继续执行剩余的函数
        }
      })
      .catch((error) => {
        console.error(error);
      });
  };
  executeNextFive(); // 开始执行
};

// 同步的解析pdf方法 - 异步调用
async function pdfToPng(pdfPath, outputFolder) {
  let pngPages = await pdfConverter.pdfToPng(
    pdfPath, // The function accepts PDF file path or a Buffer
    {
      disableFontFace: false, // When `false`, fonts will be rendered using a built-in font renderer that constructs the glyphs with primitive path commands. Default value is true.
      useSystemFonts: false, // When `true`, fonts that aren't embedded in the PDF document will fallback to a system font. Default value is false.
      enableXfa: false, // Render Xfa forms if any. Default value is false.
      viewportScale: 1, // The desired scale of PNG viewport. Default value is 1.0.
      outputFolder: outputFolder, // Folder to write output PNG files. If not specified, PNG output will be available only as a Buffer content, without saving to a file.
      outputFileMask: '', // Output filename mask. Default value is 'buffer'.
      // pdfFilePassword: '$pa$word', // Password for encrypted PDF.
      // pagesToProcess: [1, 3, 11], // Subset of pages to convert (first page = 1), other pages will be skipped if specified.
      strictPagesToProcess: false, // When `true`, will throw an error if specified page number in pagesToProcess is invalid, otherwise will skip invalid page. Default value is false.
      verbosityLevel: 0, // Verbosity level. ERRORS: 0, WARNINGS: 1, INFOS: 5. Default value is 0.
    }
  );
  pngPages = null;
  console.log(outputFolder, '解析完成！！！！');
  return '';
}
